<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      v-model="searchParams"
      :option="searchOption"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.status" @tab-change="handleTabChange">
          <el-tab-pane v-if="hasAuth(['boss.support.customer.table.enable'])" label="正常" name="01" />
          <el-tab-pane v-if="hasAuth(['boss.support.customer.table.disable'])" label="已停用" name="02" />
          <el-tab-pane v-if="hasAuth(['boss.support.customer.table.expire'])" label="已到期" name="03" />
        </el-tabs>
      </template>
      <template #header-right>
        <el-button v-if="hasAuth(['boss.support.customer.add'])" type="primary" @click="handleAddAndEdit('add', null)">
          新增客户
        </el-button>
      </template>
      <avue-crud
        v-model="formData"
        :cell-class-name="cellClassName"
        :data="tableData"
        :option="tableOption"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
        @cell-click="handleCellClick"
      >
        <template #menu="{ row }">
          <el-button text type="primary" @click="handleCheckDetail(row)"> 查看</el-button>
          <el-button
            v-if="searchParams.status == '01' && hasAuth(['boss.support.customer.update'])"
            text
            type="primary"
            @click="handleAddAndEdit('edit', row)"
          >
            编辑
          </el-button>
          <el-button
            v-if="row.status == '1' && hasAuth(['boss.support.customer.enable'])"
            text
            type="primary"
            @click="handleStopUse(row)"
          >
            停用
          </el-button>
          <el-button
            v-if="row.status == '2' && hasAuth(['boss.support.customer.enable'])"
            text
            type="primary"
            @click="handleStopUse(row)"
          >
            启用
          </el-button>
          <el-button
            v-if="row.status != '2' && row.canRenew && hasAuth(['boss.support.customer.renew'])"
            text
            type="primary"
            @click="handleRenew(row)"
          >
            续费
          </el-button>
        </template>
      </avue-crud>
    </base-table-card>
    <!-- 弹窗 -->
    <base-dialog v-model="isShowRenewDialog" :show-footer="false" title="续费" width="20%">
      <div class="px-20px">
        <CCForm ref="renewRef" :forms="state.renewForms" :gutter="10" :params="state.renewParams"></CCForm>
        <div class="text-center">
          <el-button type="primary" @click="handleConfirmRenew(state.renewParams)"> 确定续费</el-button>
        </div>
      </div>
    </base-dialog>
    <base-dialog v-model="isShowRenewalRecord" :show-footer="false" title="续费记录">
      <avue-crud :data="state.renewTableData" :option="renewTableOption"></avue-crud>
    </base-dialog>
    <base-dialog v-model="isShowApplicationNum" :show-footer="false" title="应用记录">
      <div>
        <avue-crud :data="state.appTableData" :option="appTableOption"></avue-crud>
      </div>
    </base-dialog>
    <base-drawer v-model="isShowDrawer" v-bind="drawer">
      <Detail :id="checkId" :form-data="checkInfoParams"></Detail>
    </base-drawer>
  </base-container>
</template>

<script setup>
  import CCForm from "@/views/customer/component/CCForm/index.vue";
  import { searchOption, tableOption, renewTableOption, appTableOption } from "@/crudOption/customer/list";
  import Detail from "./Detail.vue";
  import { useRouter, useRoute } from "vue-router";
  import { ElMessage, ElMessageBox } from "element-plus";
  import useCrudHook from "avue-table/useCrudHook";
  import { reactive, ref } from "vue";

  const isShowDrawer = ref(false);
  const drawer = ref({
    size: "80%",
    title: "查看客户资料",
  });
  const isShowRenewDialog = ref(false); //显示续费弹框
  const isShowRenewalRecord = ref(false); //显示续费记录
  const isShowApplicationNum = ref(false); //显示应用记录
  const renewRef = ref(null); //续费表单参数
  const checkId = ref(""); //查看详情id
  const checkInfoParams = ref({});
  const router = useRouter();
  const route = useRoute();
  const state = reactive({
    renewForms: [
      {
        itemType: "select",
        options: [
          {
            label: "1年",
            value: 1,
          },
          {
            label: "2年",
            value: 2,
          },
          {
            label: "3年",
            value: 3,
          },
          {
            label: "4年",
            value: 4,
          },
          {
            label: "5年",
            value: 5,
          },
          {
            label: "6年",
            value: 6,
          },
          {
            label: "7年",
            value: 7,
          },
          {
            label: "8年",
            value: 8,
          },
          {
            label: "9年",
            value: 9,
          },
          {
            label: "10年",
            value: 10,
          },
        ],
        label: "续费时间",
        prop: "renewalPeriod",
        rules: [
          {
            required: true,
            message: "请选择续费时间",
          },
        ],
      },
      {
        itemType: "input",
        label: "续费金额",
        prop: "renewalAmount",
        rules: [
          {
            required: true,
            message: "输入续费金额",
          },
          //正整数最多保留2位小数
          {
            pattern: /^(?!0+$)(?:[1-9]\d*(?:\.\d{1,2})?|0\.\d[1-9]\d*|0\.\d{1,2}[0-9])$/,
            message: "请输入数字，最多保留2位小数",
          },
        ],
      },
    ], //续费表单参数配置
    renewParams: {
      id: "",
      renewalAmount: "", //续费金额
      renewalPeriod: "", //续费年限
    }, //续费表单参数
    renewTableData: [], //续费表格数据
    appTableData: [], //应用表格数据
    id: "", //查看详情id
  });
  const status = ref("01");

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.customer.GetCustomerPage,
    search: { status: "01" },
    getParamsFormat: params => {
      // 开通时间
      if (params.createTime && params.createTime.length === 2) {
        params.createTimeStart = params.createTime[0];
        params.createTimeEnd = params.createTime[1];
        delete params.createTime;
      }
      // 到期时间
      if (params.expiredTime && params.expiredTime.length === 2) {
        params.expiredTimeStart = params.expiredTime[0];
        params.expiredTimeEnd = params.expiredTime[1];
        delete params.expiredTime;
      }
      // console.log(params, "params");
      // 返回查询参数
      return params;
    },
    add: Api.customer.AddCustomer,
    edit: Api.customer.UpdateCustomer,
  });

  // 跳转详情
  const handleCheckDetail = row => {
    checkId.value = row.id;
    loadCustomerDetail(row.id);
    console.log(row, "row");
  };
  const handleTabChange = value => {
    loadGetTableData();
    status.value = value;
  };

  // 获取详情接口
  const loadCustomerDetail = (id = "") => {
    Api.customer
      .CustomerDetail({ id })
      .then(res => {
        ElMessage.success("获取数据成功");
        isShowDrawer.value = !isShowDrawer.value;
        if (res.data) {
          if (res.data.businessCategory) {
            res.data.businessCategory = res.data.businessCategory.split(",");
            res.data.businessCategory = res.data.businessCategory.map(item => item * 1);
          }
          checkInfoParams.value = res.data;
          console.log(checkInfoParams.value, "checkInfoParams.value");
          // console.log(state.customerInfoParams, "customerInfoParams");
        }
      })
      .catch(error => {
        ElMessage.error(error);
      });
  };
  // 跳转续费表单
  const handleRenew = row => {
    state.renewParams = {
      id: row.id,
      renewalAmount: "", //续费金额
      renewalPeriod: 1, //续费年限
    };
    isShowRenewDialog.value = !isShowRenewDialog.value;
  };
  //续费提交接口
  const loadCustomerRenew = data => {
    Api.customer.CustomerRenew(data).then(res => {
      if (res.code == 200) {
        ElMessage.success("续费成功");
        renewRef.value.formRef.resetFields();
        console.log(111);
        loadGetTableData();
        console.log(222);
        isShowRenewDialog.value = !isShowRenewDialog.value;
      }
    });
  };
  //续费提交
  const handleConfirmRenew = params => {
    renewRef.value.formRef.validate(valid => {
      if (valid) {
        loadCustomerRenew(params);
      }
    });
  };
  //新增编辑客户
  const handleAddAndEdit = (operationType = "add", row = null) => {
    if (operationType === "add") {
      router.push({
        path: "/customer/create",
        query: { operationType: operationType },
      });
    }
    if (operationType === "edit") {
      router.push({
        path: "/customer/edit",
        query: {
          operationType: operationType,
          id: row.id,
        },
      });
    }
  };
  //停用禁用接口
  const loadCustomerEnable = data => {
    Api.customer.CustomerEnable(data).then(res => {
      if (res.code == 200) {
        ElMessage.success(res.message);
        loadGetTableData();
      }
    });
  };
  //停用禁用按钮
  const handleStopUse = row => {
    const confirmText = `${row.status == 1 ? "停用" : "启用"}`;
    ElMessageBox.confirm(`确认${confirmText}该客户吗?`, confirmText, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const status = row.status == 2 ? "1" : "2";
        loadCustomerEnable({
          id: row.id,
          status,
        });
      })
      .catch(() => {});
  };
  //续费记录接口
  const loadCustomerRenewList = params => {
    Api.customer.CustomerRenewList(params).then(res => {
      state.renewTableData = res.data;
    });
  };
  //应用记录接口
  const loadCustomerAppList = params => {
    Api.customer.CustomerAppList(params).then(res => {
      state.appTableData = res.data;
    });
  };
  //表格单元格点击事件
  const handleCellClick = (row, column) => {
    let { property } = column;
    if (property === "renewalRecord") {
      isShowRenewalRecord.value = !isShowRenewalRecord.value;
      loadCustomerRenewList({ id: row.id });
      return false;
    }
    if (property === "applicationNum") {
      isShowApplicationNum.value = !isShowApplicationNum.value;
      loadCustomerAppList({ id: row.id });
      return false;
    }
  };
  //运营模式接口
  const loadModeList = () => {
    Api.customer.ModeList().then(res => {
      if (res.data) {
        searchOption.value.formConfig.operationModeId.options = res.data.map(item => ({
          ...item,
          value: item.id.toString(),
          label: item.modeName,
        }));
      }
    });
  };

  // 改变列样式
  const cellClassName = ({ columnIndex }) => {
    if (columnIndex == 8 || columnIndex == 9) {
      return "text-blue cursor-pointer";
    }
  };
  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
    loadModeList();
  });
</script>
<style lang="scss" scoped></style>
